<template>
  <section class='f-goods-order'>
    <van-form @submit="onSubmit" input-align="right" error-message-align="right">
      <section class="f-mb-10" v-if="goodsInfo.premoneyList && goodsInfo.premoneyList.length">
        <p class="f-title">预存金额</p>
        <van-field v-model="prestoreShow" is-link readonly label="选择预存" placeholder="请选择预存" @click="showPicker = true"
          :rules="[{ required: true, message: '请选择预存' }]" />
      </section>

      <p class="f-title">实名信息</p>
      <van-field v-model="formData.idcardName" name="idcardName" label="证件姓名" placeholder="请输入证件姓名"
        :rules="[{ required: true, message: '请填写证件姓名' }]" />
      <van-field v-model="formData.idcardNum" name="idcardNum" label="证件号码" placeholder="请输入证件号码" type="tel" maxlength="18"
        :rules="[{ required: true, message: '请填写证件号码' }]" />

      <p class="f-title f-mt-10">收件信息</p>
      <van-field v-model="formData.receiveName" name="receiveName" label="收件人" placeholder="请输入收件人"
        :rules="[{ required: true, message: '请填写收件人' }]" />
      <van-field v-model="formData.receivePhone" name="receivePhone" label="联系电话" placeholder="请输入联系电话" type="tel" maxlength="11"
        :rules="[{ required: true, message: '请填写联系电话' }]" />
      <van-field v-model="cascaderName" is-link readonly label="所在区域" placeholder="请选择所在地区" @click="off.cascader = true"
        :rules="[{ required: true, message: '请选择所在地区' }]" />
      <van-field v-model="formData.receiveAddressDetail" name="receiveAddressDetail" label="详细地址" placeholder="请输入详细地址"
        :rules="[{ required: true, message: '请填写详细地址' }]" />

      <section v-if="goodsInfo.chooseNumType == 2 && phoneList.length">
        <p class="f-title f-mt-10">选择号码</p>
        <van-field v-model="formData.phone" is-link readonly label="选择号码" placeholder="请选择一个心仪号码" @click="off.phone = true"
          :rules="[{ required: true, message: '请选择号码' }]" />
      </section>

      <div class="f-submit-btn">
        <van-button round block type="primary" native-type="submit">提交订单</van-button>
      </div>
    </van-form>

    <van-popup v-model:show="off.cascader" round position="bottom">
      <van-cascader v-model="cascaderValue" title="请选择所在地区" :options="areaList" :field-names="fieldNames"
        @close="off.cascader = false" @finish="onFinish" />
    </van-popup>

    <van-popup v-model:show="showPicker" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">选择{{pickerTitle}}</p>
      <van-picker ref="pickerRef" :columns="columns" :show-toolbar="false" />

      <div class="f-popup-btn">
        <van-button block type="primary" @click="handlePicker()">确定</van-button>
      </div>
    </van-popup>

    <van-popup v-model:show="off.phone" position="bottom" closeable close-icon-position="top-left" :style="{ minHeight: '30%' }">
      <section class="f-phone-content">
        <p class="f-phone-title">选择号码</p>
        <ul class="f-phone-list">
          <li v-for="(item,index) in phoneList" :key="index" :class="{'f-select':formData.phone == item.phone}"
            @click="formData.phone = item.phone">
            {{item.phone}}
          </li>
          <template v-if="phoneList.length%3 == 1">
            <li v-for="(item,index) in 2" :key="index" style="border:none"></li>
          </template>
          <li v-if="phoneList.length%3 == 2" style="border:none"></li>
        </ul>
        <div class="f-flex-ct f-mt-05" @click="getPhoneQry()">
          <img style="width:19px;height:16px" src="@/assets/icons/icon_change_orange.png" alt="">
          <p class="f-ml-05" style="font-size: 14px;color: #FF8010;">换一批</p>
        </div>

        <div class="f-submit-btn">
          <van-button round block type="primary" native-type="submit" @click="off.phone = false">确定</van-button>
        </div>
      </section>
    </van-popup>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute, START_LOCATION } from 'vue-router'
import { useStore } from 'vuex';
import api from '../api'
import { Base64 } from 'js-base64'
import { successDeal } from '@/utils/utils';

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const pickerRef = ref()

    const state = reactive({
      off: {
        cascader: false,
        phone: false,
      },

      goodsId: '',

      cascaderName: "",
      cascaderValue: "",
      areaList: [],
      fieldNames: {
        text: 'systemAreaName',
        value: 'systemAreaId',
      },

      formData: {
        "areaAreaId": "",
        "cityAreaId": "",
        "goodsId": "",
        "idcardName": "",
        "idcardNum": "",
        "phone": "",
        "prestoreShow": "",
        "provinceAreaId": "",
        "receiveAddressDetail": "",
        "receiveName": "",
        "receivePhone": ""
      },
      prestoreShow: "",

      phoneList: [],
      selectPhone: "",

      pickerTitle: '预存',
      showPicker: false,
      columns: [],
      customFieldName: {
        text: 'text',
        value: 'value',
        children: 'children'
      },

      goodsInfo: {}
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '提交订单',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightType: 'search',
        bg: ''
      });

      state.goodsId = route.query.goodsId
      getArea(state.goodsId)
      getGoodsDetail(state.goodsId)
    })

    const getArea = (goodsId) => {
      let json = {
        goodsId
      }
      api.areaByGoods(json).then(res => {
        state.areaList = res.data.list
      })
    }

    const getGoodsDetail = (goodsId) => {
      let json = {
        goodsId
      }
      api.goodsDetail(json).then(res => {
        state.goodsInfo = res.data
        if (res.data.premoneyList) {
          let premoneyList = []
          res.data.premoneyList.forEach(item => {
            let obj = {
              text: `${item.activityTitle}元`,
              value: item.showMoney
            }
            premoneyList.push(obj)
          })
          state.columns = premoneyList
        }
      })
    }

    // 全部选项选择完毕后，会触发 finish 事件
    const onFinish = ({ selectedOptions }) => {
      state.off.cascader = false
      let cascaderName = []
      selectedOptions.forEach((item, index) => {
        cascaderName.push(item.systemAreaName)
        if (index == 0) state.formData.provinceAreaId = item.systemAreaId
        if (index == 1) state.formData.cityAreaId = item.systemAreaId
        if (index == 2) state.formData.areaAreaId = item.systemAreaId
      });
      state.cascaderName = cascaderName.join('/')

      if (state.goodsInfo.chooseNumType == 2) {
        getPhoneQry()
      }
    };

    const getPhoneQry = () => {
      let json = {
        "currentPage": "1",
        "fuzzyKey": "",
        "fuzzyTag": "0",
        "goodsId": state.goodsId,
        "pageSize": "30",
        "systemAreaId": state.cascaderValue
      }
      api.phoneQry(json).then(res => {
        state.phoneList = res.data.list
      })
    }

    const onSubmit = (values) => {
      let json = JSON.parse(JSON.stringify(state.formData))
      json.goodsId = state.goodsId
      json.idcardName = Base64.encode(json.idcardName)
      json.idcardNum = Base64.encode(json.idcardNum)
      api.orderSubmit(json).then(res => {
        if (res.data.topay) {
          successDeal('订单提交成功，请支付')
          setTimeout(() => {
            router.replace({
              path: '/goods/pay',
              query: {
                sysOrderId: res.data.sysOrderId
              }
            })
          }, 500)
        } else {
          successDeal('订单提交成功！')
          setTimeout(() => {
            router.go(-1)
          }, 500)
        }
      })
    };

    const handlePicker = (e) => {
      let data = pickerRef.value.confirm().selectedOptions[0]
      state.formData.prestoreShow = data.value
      state.prestoreShow = data.text
      state.showPicker = false
    }

    return {
      ...toRefs(state),
      pickerRef,
      onFinish,
      onSubmit,
      handlePicker,
      getPhoneQry
    }
  }
}
</script>
<style lang='scss' scoped>
.f-goods-order {
  .f-submit-btn {
    margin-top: 30px;
    margin-bottom: 30px;
    padding: 0 62px;
  }
  .f-title {
    background: #fff;
    font-size: 14px;
    color: #000000;
    padding: 16px 14px 10px 14px;
  }
  .f-title::before {
    content: "";
    display: inline-block;
    width: 3px;
    height: 11px;
    background: #488bfe;
    margin-right: 4px;
  }
  .f-phone-content {
    .f-phone-title {
      font-size: 16px;
      color: #000000;
      padding: 16px 0;
      text-align: center;
      border-bottom: 1px solid #aaaaaa;
    }
    .f-phone-list {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      margin-top: 5px;
      padding: 15px 10px;
      li {
        color: #000000;
        border: 1px solid #aaaaaa;
        font-size: 12px;
        text-align: center;
        margin-bottom: 15px;
        padding: 5px 0px;
        width: 30%;
      }
      .f-select {
        border: 1px solid #ff8010;
        background: #ff8010;
        color: #fff;
      }
    }
  }
}
</style>